package com.wly.jdbc;

import com.wly.domain.Student;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author wly
 * @Create 2023-04-30 10:19
 * @Description:
 */
public class JDBCDemo4 {

    /**
     * 查询所有student对象
     * @return
     */
    public List<Student> findAll(){
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<Student> students = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
            String sql = "select * from student";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            Student student = null;
            students = new ArrayList<Student>();
            while (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                String sex = rs.getString("sex");
                String address = rs.getString("address");
                //创建student对象，并赋值
                student = new Student();
                student.setId(id);
                student.setName(name);
                student.setAge(age);
                student.setSex(sex);
                student.setAddress(address);
                students.add(student);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (stmt != null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return students;
    }

    public static void main(String[] args) {
        JDBCDemo4 jdbcDemo4 = new JDBCDemo4();
        List<Student> list = jdbcDemo4.findAll();
        System.out.println(list);
    }
}
